﻿Imports System.Runtime.InteropServices
Imports System.Collections.ObjectModel
Imports SlimDX.Direct3D9
Imports SlimDX
Imports Microsoft.Win32
Imports System.IO
Imports System.Net

Public Class frmMain
#Region "Render Loop"
    <System.Security.SuppressUnmanagedCodeSecurity()> _
   Private Declare Function PeekMessage Lib "User32.dll" Alias "PeekMessageA" ( _
      ByRef msg As MessageStruct, _
      ByVal hWnd As IntPtr, _
      ByVal messageFilterMin As Integer, _
      ByVal messageFilterMax As Integer, _
      ByVal flags As Integer _
   ) As Integer
    <StructLayout(LayoutKind.Sequential)> _
   Public Structure MessageStruct
        Public HWnd As IntPtr
        Public Msg As System.Windows.Forms.Message
        Public WParam As IntPtr
        Public LParam As IntPtr
        Public Time As Integer
        Public P As System.Drawing.Point
    End Structure
    Protected Function _AppIsIdle() As Boolean
        Dim msg As MessageStruct

        Return (PeekMessage(msg, IntPtr.Zero, 0, 0, 0) = 0)
    End Function
    Protected Sub OnApplicationIdle(ByVal sender As Object, ByVal e As EventArgs)
        Do While _AppIsIdle()
            If Not ActiveForm Is Me Then
                System.Threading.Thread.Sleep(200)
            End If
            If DXLoaded Then DirectX.Render()
        Loop
    End Sub
    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
#If Not Debug Then
        shaderWindow.CloseAction = TD.SandDock.DockControlCloseAction.Dispose
        shaderWindow.Close()
        DebugMenu.Visible = False
#End If

        Me.SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.Opaque, True)
        AddHandler System.Windows.Forms.Application.Idle, AddressOf Me.OnApplicationIdle

    End Sub

    Dim Mouse As Point



    Private Sub Panel1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles renderPanel.MouseClick
        If e.Button = System.Windows.Forms.MouseButtons.Right Then
            If Not ctrlKey And Not shiftKey Then
                If Not IsNothing(SelectedScenario) Then
                    'If SelectedScenario.SelectedObject.hitIndex > -1 Then
                    '    If SelectedScenario.SelectedObject.Palette Is Nothing Then Exit Sub
                    '    Dim nMenu As New ContextMenu
                    '    For x As Integer = 0 To SelectedScenario.SelectedObject.Palette.Length - 1
                    '        nMenu.MenuItems.Add(SelectedScenario.SelectedObject.Palette(x).name, New System.EventHandler(AddressOf ChangeTypeSelected))
                    '    Next
                    '    If SelectedScenario.SelectedObject.Palette.Length > 0 Then 
                    'End If
                    ' If Not SelectedScenario.SelectedObject.blockName Is Nothing Then
                    Dim nMenu As ContextMenuStrip = SelectedScenario.CreateContext
                    nMenu.Tag = e.Location
                    If Not nMenu Is Nothing Then
                        nMenu.Show(renderPanel, e.Location)
                    End If
                    'End If
                End If
            End If
        End If
    End Sub
    Private Sub ChangeTypeSelected(ByVal sender As Object, ByVal e As EventArgs)
        Dim nItem As MenuItem = sender
        If Not IsNothing(SelectedScenario) Then
            If Not SelectedScenario.SelectedObject.hitIndex Is Nothing Then
                '  SelectedScenario.ChangeObject(nItem.Parent.MenuItems.IndexOf(nItem))
            End If
        End If
    End Sub
    Private Sub formMain_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles renderPanel.MouseDown
        If e.Button = System.Windows.Forms.MouseButtons.Middle Then
            Me.Focus()
            MouseChange(True)
        ElseIf e.Button = System.Windows.Forms.MouseButtons.Left Then
            If Not IsNothing(SelectedScenario) Then
                If Not ctrlKey And Not shiftKey Then
                    SelectedScenario.SelectObject(e.X, e.Y)
                    selectedobjectWindow.Controls.Clear()
                    If Not SelectedScenario.SelectedObject.blockName Is Nothing Then
                        Dim nBlocks(SelectedScenario.SelectedObject.blockName.Length - 2) As String
                        Array.Copy(SelectedScenario.SelectedObject.blockName, 1, nBlocks, 0, nBlocks.Length)
                        Dim nReflexive As ctrReflexive = GetReflexive(nBlocks, SelectedScenario.scnrTag(SelectedScenario.SelectedObject.blockName(0)), SelectedScenario.scnrTag.Xpe.FieldByName(SelectedScenario.SelectedObject.blockName(0)), SelectedScenario.scnrTag(SelectedScenario.SelectedObject.Extension), SelectedScenario.SelectedObject.hitIndex)
                        If Not nReflexive Is Nothing Then
                            selectedobjectWindow.Controls.Add(nReflexive)
                            nReflexive.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowOnly
                            nReflexive.Location = New Point(0, 0)
                        End If

                    End If
                End If
            End If
        ElseIf e.Button = System.Windows.Forms.MouseButtons.Right Then
        End If
    End Sub
    Private Function GetReflexive(ByVal blocks() As String, ByVal currentBlock As Array, ByVal currentField As Magic.Core.Xpe.Field, ByVal palette As Array, ByVal hitIndex() As Integer) As ctrReflexive
        If currentBlock Is Nothing Then Return Nothing
        Dim blockName As String = blocks(0)
        Dim objCount As Integer = currentBlock.GetLength(0)
        If blocks.Length = 1 Then
            Dim nReflexive As New ctrReflexive(currentBlock, currentField, "")
            nReflexive.cmbBlockIndex.SelectedIndex = hitIndex(0)
            'nReflexive.tspBloc.Visible = False
            Return nReflexive
        Else
            Dim nBlocks(blocks.Length - 2) As String
            Array.Copy(blocks, 1, nBlocks, 0, nBlocks.Length)

            Dim nHit(hitIndex.Length - 2) As Integer
            Array.Copy(hitIndex, 1, nHit, 0, nHit.Length)

            Dim objBlock As Array = CType(currentBlock.GetValue(hitIndex(0), currentField.Item(blockName)), Array)
            Dim objField As Magic.Core.Xpe.Field = currentField.FieldByName(blockName)

            Return GetReflexive(nBlocks, objBlock, objField, palette, nHit)
        End If
    End Function
    Private Sub formMain_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles renderPanel.MouseUp
        MouseChange(False)
    End Sub
    Private Sub formMain_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles renderPanel.MouseMove
        If e.Button = System.Windows.Forms.MouseButtons.Left Then
            If ctrlKey Then
                If Not IsNothing(SelectedScenario) Then SelectedScenario.MoveObject(e.X, e.Y)
            End If

            If shiftKey Then
                If Not IsNothing(SelectedScenario) Then
                    If Mouse.X = 0 And Mouse.Y = 0 Then
                        Mouse = New Drawing.Point(e.X, e.Y)
                    End If

                    Dim Rotation As Vector3 = SelectedScenario.ObjectRotation

                    Dim xd As Integer = e.X - Mouse.X
                    Dim yd As Integer = e.Y - Mouse.Y

                    'Adjust yaw
                    Rotation.X += CSng(xd / 200)

                    SelectedScenario.ObjectRotation = Rotation

                    Mouse = New Drawing.Point(e.X, e.Y)
                End If
            End If

        ElseIf e.Button = System.Windows.Forms.MouseButtons.Right Then
            If shiftKey Then
                If Not IsNothing(SelectedScenario) Then
                    If Mouse.X = 0 And Mouse.Y = 0 Then
                        Mouse = New Drawing.Point(e.X, e.Y)
                    End If

                    Dim Rotation As Vector3 = SelectedScenario.ObjectRotation

                    Dim xd As Integer = e.X - Mouse.X
                    Dim yd As Integer = e.Y - Mouse.Y

                    'Adjust roll and pitch
                    Rotation.Y += CSng(yd / 200)
                    Rotation.Z -= CSng(xd / 200)

                    SelectedScenario.ObjectRotation = Rotation

                    Mouse = New Drawing.Point(e.X, e.Y)
                End If
            End If
            If ctrlKey Then
                If Not IsNothing(SelectedScenario) Then
                    'SelectedScenario.BSPS(SelectedScenario.SelectedBSPIndex).SetColor(e.X, e.Y, sprayColor.BackColor)
                End If
            End If
        ElseIf e.Button = System.Windows.Forms.MouseButtons.None Then
            Mouse = New Drawing.Point(0, 0)
        End If
    End Sub
#End Region
    Dim DXLoaded As Boolean = False

    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        appSettings.WindowPlacements = sdManager.GetLayout
        appSettings.Save()
    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        MainForm = Me
        ' Settings.WriteSettings()
        appSettings = Settings.Load()
        If appSettings Is Nothing Then
            appSettings = New Settings
            Dim nFrm As New frmSettings
            If nFrm.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then

            End If
        End If
        MagicInterface.Load(Me.lblStatus)
        DXLoaded = DirectX.InitializeDX(renderPanel)
        RichTextBox1.Text = System.Text.ASCIIEncoding.Default.GetString(My.Resources.shader_transparent_water)

        If appSettings.WindowPlacements <> "" Then
            Dim prevLayout As String = sdManager.GetLayout
            Try
                sdManager.SetLayout(appSettings.WindowPlacements)
            Catch ex As Exception
                sdManager.SetLayout(prevLayout)
            End Try
        End If

        If Not System.IO.Directory.Exists(appSettings.XboxTagFolder) Then
            'System.IO.Directory.CreateDirectory(appSettings.XboxTagFolder)
        End If

        RefreshFiles()

        For x As Integer = 0 To sdManager.GetDockControls.Count - 1
            ' If sdManager.GetDockControls(x).Visible = True Then
            Dim nItem As New ToolStripMenuItem(sdManager.GetDockControls(x).Text, sdManager.GetDockControls(x).TabImage, AddressOf ShowWindow)
            nItem.Tag = sdManager.GetDockControls(x)
            WindowsToolStripMenuItem.DropDownItems.Add(nItem)
            ' End If
        Next

    End Sub
    Sub ShowWindow(ByVal sender As Object, ByVal e As EventArgs)
        Dim nItem As ToolStripMenuItem = sender
        CType(nItem.Tag, TD.SandDock.DockControl).Open()
    End Sub

    Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
        If Not e.Node Is Nothing Then
            If IsNumeric(e.Node.Tag) Then
                Dim Found As Boolean = False
                For Each tP As TD.SandDock.TabbedDocument In tabManager.Documents
                    If tP.Tag = e.Node.Tag Then
                        Found = True
                        tP.Select()
                    End If
                Next
                If Not Found Then
                    Dim mTag As Magic.Core.Tag = magicMap.Library(e.Node.Tag)
                    Dim tTag As New ctrTag(mTag, mTag.Xpe)
                    Dim tPage As New TD.SandDock.TabbedDocument(tabManager, tTag, e.Node.Text)
                    tPage.Open()
                    tPage.Text = e.Node.Text
                    tPage.Tag = e.Node.Tag
#If DEBUG Then
                    Select Case mTag.Xpe.Extension
                        Case "model"

                            'Dim nModel As New Model(mTag)
                            'SelectedModel = nModel

                        Case "bitmap"
                            'Bitmap.Deswizzle(mTag)
                            'Dim nBitmap As New Bitmap(mTag)
                            'Texture.ToFile(nBitmap.Texture, "C:\Surfaces\Saved.dds", ImageFileFormat.Dds)
                            'CubeTexture.ToFile(nBitmap.Cube(0, False, 6), "C:\Surfaces\SavedCubeMips.dds", ImageFileFormat.Dds)
                        Case "scenario_structure_bsp"
                            'mTag("lightmaps") = Nothing

                            'Dim bspLightmaps As Array = mTag("structure lightmaps")
                            'For x As Integer = 0 To bspLightmaps.GetLength(0) - 1
                            'bspLightmaps.SetValue(-1, x, 0)
                            'Next
                            'mTag("structure lightmaps") = bspLightmaps

                            'mTag.Write("C:\Tags\damnation.scenario_structure_bsp", magicMap.Library)
                        Case "scenario"
                            'SwapScripts(mTag)

                            'mTag.Write("C:\Tags\damnation.scenario", magicMap.Library)
                    End Select
#End If
                End If
            ElseIf e.Node.Tag = "DBTAG" Then
                If e.Node.Text.EndsWith("scenario") Then
                    If SelectedScenario Is Nothing Then
                        'Dim sp As New Stopwatch
                        'sp.Start()
                        MagicInterface.OpenMap(appSettings.XboxTagFolder & e.Node.FullPath, TreeView1)
                        'sp.Stop()
                        'Console.WriteLine("Magic method time: " & sp.Elapsed.ToString)
                        'sp.Restart()
                        'Dim hMap As New HaloMap(appSettings.XboxTagFolder & "\" & e.Node.FullPath)
                        'sp.Stop()
                        'Console.WriteLine("Arsenic method time: " & sp.Elapsed.ToString)

                        For x As Integer = 0 To magicMap.Library.Count - 1
                            If magicMap.Library(x).Xpe.Extension = "globals" Then
                                Globals.LoadDefaultTextures(magicMap.Library(x))
                                Exit For
                            End If
                        Next
                        For x As Integer = 0 To magicMap.Library.Count - 1
                            If magicMap.Library(x).Xpe.Extension = "scenario" Then
                                Managers.Clear()
                                SelectedScenario = New Scenario(magicMap.Library(x))
                                Camera.Update = True
                                ToolStripComboBox1.Items.Clear()

                                For b As Integer = 0 To SelectedScenario.BSPS.Count - 1
                                    Dim StartIndex As Integer = SelectedScenario.BSPS(b).Name.LastIndexOf("\") + 1
                                    Dim StopIndex As Integer = SelectedScenario.BSPS(b).Name.LastIndexOf(".")
                                    ToolStripComboBox1.Items.Add(SelectedScenario.BSPS(b).Name.Substring(StartIndex, StopIndex - StartIndex))
                                Next
                                ToolStripComboBox1.SelectedIndex = 0

                                cmbScript.Items.Clear()
                                For b As Integer = 0 To Scripts.Scripts.Count - 1
                                    cmbScript.Items.Add(Scripts.Scripts(b).Name)
                                Next
                                If cmbScript.Items.Count > 0 Then cmbScript.SelectedIndex = 0
                                Exit For
                            End If
                        Next
                        TreeView1.BeginUpdate()
                        For x As Integer = 0 To magicMap.Library.Count - 1
                            TagNodes(magicMap.Library(x).Name, TreeView1.Nodes, x)
                        Next
                        TreeView1.EndUpdate()
                    End If
                End If
            End If
        End If
    End Sub
    Private Sub TagNodes(ByVal NodePath As String, ByVal Nodes As TreeNodeCollection, ByVal TagIndex As Integer)
        Dim sHierarchy() As String = NodePath.Split("\")

        If sHierarchy.Count = 1 Then
            Dim nIndex As Integer = FindNode(NodePath, Nodes)
            If nIndex > -1 Then
                'Nodes(nIndex).ImageIndex = 0
                'Nodes(nIndex).SelectedImageIndex = 0
                Nodes(nIndex).Tag = TagIndex
            End If
        Else
            Dim nPath As String = ""
            For x As Integer = 1 To sHierarchy.Count - 1
                nPath &= sHierarchy(x) & IIf(x < sHierarchy.Count - 1, "\", "")
            Next

            Dim nIndex As Integer = FindNode(sHierarchy(0), Nodes)

            If nIndex > -1 Then
                TagNodes(nPath, Nodes(nIndex).Nodes, TagIndex)
            End If
        End If

    End Sub
    Private Function FindNode(ByVal nText As String, ByVal Nodes As TreeNodeCollection) As Integer
        For x As Integer = 0 To Nodes.Count - 1
            If Nodes(x).Text.ToLower = nText.ToLower Then Return x
        Next
        Return -1
    End Function
    Private Sub XboxMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles XboxMapToolStripMenuItem.Click

    End Sub

    Private Sub TreeView1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TreeView1.MouseMove
        If e.Button = System.Windows.Forms.MouseButtons.Left Then
            If Not IsNothing(TreeView1.SelectedNode) Then
                Try

                    TreeView1.SelectedNode = TreeView1.GetNodeAt(e.Location)
                    Dim tagDetail(1) As String
                    tagDetail(0) = TreeView1.SelectedNode.FullPath.Replace(System.IO.Path.GetExtension(TreeView1.SelectedNode.Text), "")
                    tagDetail(1) = cxpe.FromExtension(System.IO.Path.GetExtension(TreeView1.SelectedNode.Text).Replace(".", "")).FourCC

                    'Dim tagIndex As Integer = magicMap.Library.GetDependencyTag(tagName, tagType, appSettings.XboxTagFolder, appSettings.CETagFolder)
                    TreeView1.DoDragDrop(tagDetail, DragDropEffects.Link)
                Catch ex As Exception

                End Try
            End If

        End If
    End Sub

    Private Sub Panel1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles renderPanel.DragEnter
        If (e.Data.GetDataPresent("System.String[]")) Then
            ' Display the copy cursor.
            e.Effect = DragDropEffects.Link
        Else
            ' Display the no-drop cursor.
            e.Effect = DragDropEffects.None
        End If

    End Sub
    Private Sub Panel1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles renderPanel.DragDrop
        Dim tagDetail() As String = e.Data.GetData("System.String[]")
        Dim tagIndex As Integer = magicMap.Library.GetDependencyTag(tagDetail(0), tagDetail(1), appSettings.XboxTagFolder, appSettings.CETagFolder)

        SelectedScenario.DropObject(tagIndex, e.X, e.Y)
    End Sub



    Private Sub MapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MapToolStripMenuItem.Click
        Dim OFD As New OpenFileDialog
        OFD.Filter = "Halo Map (*.map)|*.map"
        If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            Dim nMap As New Magic.Core.HaloMap(OFD.FileName, appSettings.CETagFolder, appSettings.CEMapFolder & "\bitmaps.map", appSettings.CEMapFolder & "\sounds.map", appSettings.XboxTagFolder, cxpe, Me.lblStatus)
            For t As Integer = 0 To nMap.Library.Count - 1
                If Not nMap.Library(t) Is Nothing Then nMap.Library(t).Dirty()
            Next
            nMap.SaveAsTagCollection(appSettings.XboxTagFolder)
            nMap.Dispose()
            nMap = Nothing
            RefreshFiles()
        End If
    End Sub

    Private Sub SettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SettingsToolStripMenuItem.Click
        Dim nFrm As New frmSettings
        If nFrm.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            appSettings.Save()
            RefreshFiles()
        End If
    End Sub

    Private Sub CompileShaderToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompileShaderToolStripMenuItem.Click
        Try
            Dim sEffect As Effect = Effect.FromString(xDevice, RichTextBox1.Text, Nothing, Nothing, ShaderFlags.None, Nothing)
            swatEffect = sEffect
        Catch ex As Exception
            ConsoleMessage("Shader did not compile...")
        End Try
    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim fAbout As New frmAbout
        fAbout.ShowDialog()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private Sub SaveScenarioToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveScenarioToolStripMenuItem.Click
        If SelectedScenario Is Nothing Then Exit Sub
        magicMap.SaveAsTagCollection(appSettings.XboxTagFolder, True)
    End Sub

    Private Sub DiscussionMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DiscussionMenu.Click
        Process.Start("http://www.halomaps.com/forum/index.php/board,69.0.html")
    End Sub

    Private Sub BugMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BugMenu.Click
        Process.Start("http://www.halomaps.com/forum/index.php/board,70.0.html")
    End Sub

    Private Sub TutorialMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TutorialMenu.Click
        Process.Start("http://www.halomaps.com/forum/index.php/board,71.0.html")
    End Sub

    Private Sub XBOXMapsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles XBOXMapsToolStripMenuItem.Click
        Dim mapfiles As ReadOnlyCollection(Of String)
        mapfiles = My.Computer.FileSystem.GetFiles(appSettings.XboxMapFolder, FileIO.SearchOption.SearchAllSubDirectories, "*.map")
        For x As Integer = 0 To mapfiles.Count - 1
            Dim nMap As New Magic.Core.HaloMap(mapfiles(x), appSettings.CETagFolder, appSettings.CEMapFolder & "\bitmaps.map", appSettings.CEMapFolder & "\sounds.map", appSettings.XboxTagFolder, cxpe, Me.lblStatus)
            For t As Integer = 0 To nMap.Library.Count - 1
                If Not nMap.Library(t) Is Nothing Then nMap.Library(t).Dirty()
            Next
            nMap.SaveAsTagCollection(appSettings.XboxTagFolder)
            'magicMap = nMap
            'Scripts.LoadScripts(magicMap.Library(0))
            nMap.Dispose()
            nMap = Nothing
        Next
        RefreshFiles()
    End Sub

    Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
        If SelectedScenario Is Nothing Then Exit Sub
        Dim ScenarioName As String = SelectedScenario.scnrTag.Name.Replace(appSettings.XboxTagFolder & "\", "").Replace(".scenario", "")
        Dim newScenario As String = InputBox("New Scenario name.", "Save As", ScenarioName)
        If newScenario = "" Then Exit Sub
        magicMap.SaveAsTagCollection(appSettings.XboxTagFolder, True, newScenario)
        RefreshFiles()
    End Sub
    Sub RefreshFiles()
        If Not Directory.Exists(appSettings.XboxTagFolder) Then Exit Sub
        files = My.Computer.FileSystem.GetFiles(appSettings.XboxTagFolder, FileIO.SearchOption.SearchAllSubDirectories, "*.*")
        MagicInterface.DisplayTreeDB(TreeView1, files)
        If Not magicMap Is Nothing Then
            TreeView1.BeginUpdate()
            For x As Integer = 0 To magicMap.Library.Count - 1
                TagNodes(magicMap.Library(x).Name, TreeView1.Nodes, x)
            Next
            TreeView1.EndUpdate()
        End If
    End Sub

    Private Sub CreateMD5TableToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CreateMD5TableToolStripMenuItem.Click
        'cxpe.GetMD5Table(appSettings.XboxTagFolder, appSettings.CETagFolder, lblStatus)
        Dim mapfiles As ReadOnlyCollection(Of String)
        mapfiles = My.Computer.FileSystem.GetFiles(appSettings.XboxTagFolder, FileIO.SearchOption.SearchAllSubDirectories, "*.scenario")
        For x As Integer = 0 To mapfiles.Count - 1
            Dim nMap As New Magic.Core.HaloMap(mapfiles(x), appSettings.CETagFolder, appSettings.CEMapFolder & "\bitmaps.map", appSettings.CEMapFolder & "\sounds.map", appSettings.XboxTagFolder, cxpe, Me.lblStatus)

            For tag As Integer = nMap.Library.Count - 1 To 0 Step -1
                cxpe.RootTag = tag
                lblStatus.Text = "Hashing '" & nMap.Library(tag).Name & nMap.Library(tag).Xpe.Extension & "''"
                If Not cxpe.HashExists(nMap.Library(tag).Name) Then

                    cxpe.AddHash(nMap.Library(tag).Name, nMap.Library(tag).ReturnHash(nMap.Library))
                End If

                Application.DoEvents()
            Next
            cxpe = nMap.Library.CXPE
            nMap.Dispose()
            nMap = Nothing
        Next
        cxpe.GetMD5Table()

    End Sub

    Private Sub ToFTPToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToFTPToolStripMenuItem.Click
        If magicMap Is Nothing Then Exit Sub

        Dim tempPath As String = System.IO.Path.GetTempFileName
        Dim nInternal As New frmInternal
        If nInternal.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            magicMap.SaveAsXbox(tempPath, appSettings.PAL_Version, nInternal.Internal.Text, True)
        End If

        Try
            Dim FTP As New FTP(appSettings.FTP_Address, appSettings.FTP_Directory, appSettings.FTP_Username, appSettings.FTP_Password, 21)
            AddHandler FTP.ProgressChanged, AddressOf ProgressChanged
            FTP.DeleteFile(nInternal.Internal.Text & ".map")
            FTP.UploadFile(tempPath, nInternal.Internal.Text & ".map")
            FTP.CloseConnection()
            ProgressChanged(0)
            lblStatus.Text = "FTP Finished."
        Catch
            lblStatus.Text = "FTP Error occured. Make sure your xbox is on and is at the dashboard."
        End Try
    End Sub
    Sub ProgressChanged(ByVal percentage As Integer)
        barProgress.Value = percentage
        Application.DoEvents()
    End Sub

    Private Sub UploadMapToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UploadMapToolStripMenuItem.Click
        'If magicMap Is Nothing Then Exit Sub
        Dim OFD As New OpenFileDialog
        If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then

            Dim nInternal As New frmInternal
            If nInternal.ShowDialog = System.Windows.Forms.DialogResult.OK Then
                Dim ER As New Magic.Core.EndianWriter(New IO.FileStream(OFD.FileName, IO.FileMode.Open), Magic.Core.ByteOrder.LittleEndian)
                ER.Position = 32
                For x As Integer = 0 To 32 - 1
                    ER.Write(CByte(0))
                Next
                ER.Position = 32
                ER.Write(nInternal.Internal.Text, False)
                ER.Close()

                Try

                    Dim FTP As New FTP(appSettings.FTP_Address, appSettings.FTP_Directory, appSettings.FTP_Username, appSettings.FTP_Password, 21)
                    AddHandler FTP.ProgressChanged, AddressOf ProgressChanged
                    FTP.DeleteFile(nInternal.Internal.Text & ".map")
                    FTP.UploadFile(OFD.FileName, nInternal.Internal.Text & ".map")
                    FTP.CloseConnection()
                    ProgressChanged(0)
                    lblStatus.Text = "FTP Finished."
                Catch
                    lblStatus.Text = "FTP Error occured. Make sure your xbox is on and is at the dashboard."
                End Try


            End If
        End If
    End Sub

    Private Sub DeleteCacheToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteCacheToolStripMenuItem.Click
        Try

            Dim FTP As New FTP(appSettings.FTP_Address, "X\", appSettings.FTP_Username, appSettings.FTP_Password, 21)
            AddHandler FTP.ProgressChanged, AddressOf ProgressChanged

            Dim FtpFiles() As String = FTP.GetFileList("cache*.map")
            For x As Integer = 0 To FtpFiles.Count - 2
                FTP.DeleteFile(FtpFiles(x))
            Next

            FTP.ChangeDirectory("\Y\")
            FtpFiles = FTP.GetFileList("cache*.map")
            For x As Integer = 0 To FtpFiles.Count - 2
                FTP.DeleteFile(FtpFiles(x))
            Next

            FTP.ChangeDirectory("\Z\")
            FtpFiles = FTP.GetFileList("cache*.map")
            For x As Integer = 0 To FtpFiles.Count - 2
                FTP.DeleteFile(FtpFiles(x))
            Next

            FTP.CloseConnection()
            ProgressChanged(0)
            lblStatus.Text = "Cache Cleared."
        Catch
            lblStatus.Text = "FTP Error occured. Make sure your xbox is on and is at the dashboard."
        End Try
    End Sub

    Private Sub renderPanel_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles renderPanel.Resize
        renderPanel.Invalidate()
    End Sub

    Private Sub TreeView1_DrawNode(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawTreeNodeEventArgs) Handles TreeView1.DrawNode
        If Integer.TryParse(e.Node.Tag, New Integer) Then
            If e.Bounds.X > -1 And e.Bounds.Height > 0 Then
                e.DrawDefault = False

                Dim nFont As New Drawing.Font(e.Node.TreeView.Font, FontStyle.Underline)
                If e.State = TreeNodeStates.Selected Then
                    e.Graphics.DrawString(e.Node.Text, nFont, System.Drawing.SystemBrushes.HighlightText, e.Bounds.Location)
                Else
                    e.Graphics.DrawString(e.Node.Text, nFont, System.Drawing.SystemBrushes.WindowText, e.Bounds.Location)
                End If

            Else
                e.DrawDefault = True
            End If
        Else
            e.DrawDefault = True
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If Not SelectedScenario Is Nothing Then
            Dim Raw() As Byte = SelectedScenario.BSPS(SelectedScenario.SelectedBSPIndex).Originals
            Dim Raw2(Raw.Length - 1) As Byte
            Array.Copy(Raw, Raw2, Raw.Length)

            For b As Integer = 0 To Raw.Count / 2 - 1
                Dim cColor As Color = DecompressColor(BitConverter.ToInt16(Raw, b * 2))
                cColor = Color.FromArgb(cColor.R * TrackBar1.Value / TrackBar1.Maximum * redBar.Value / redBar.Maximum, cColor.G * TrackBar1.Value / TrackBar1.Maximum * greenBar.Value / greenBar.Maximum, cColor.B * TrackBar1.Value / TrackBar1.Maximum * blueBar.Value / blueBar.Maximum)

                Dim comInt As Integer = CompressColor(cColor)
                Array.Copy(BitConverter.GetBytes(BitConverter.ToInt16(BitConverter.GetBytes(comInt), 0)), 0, Raw2, b * 2, 2)
            Next
            SelectedScenario.BSPS(SelectedScenario.SelectedBSPIndex).lightmapTag(19) = Raw2

            SelectedScenario.BSPS(SelectedScenario.SelectedBSPIndex).InitLightmaps()
        End If
    End Sub

    Private Sub sprayColor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sprayColor.Click
        Dim sColor As New ColorDialog
        sColor.SolidColorOnly = True
        If sColor.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            sprayColor.BackColor = sColor.Color
        End If
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        'If Not SelectedScenario Is Nothing Then
        '    Dim Raw(lightmapTag("bitmaps").GetValue(lightMap, 10)(1)) As Byte
        '    Array.Copy(lightmapTag("bitmaps").GetValue(lightMap, 19), lightmapTag("bitmaps").GetValue(lightMap, 10)(0), Raw, 0, Raw.Length)

        '    Dim BitmapWidth As Integer = lightmapTag("bitmaps").GetValue(lightMap, 1)
        '    Dim BitmapHeight As Integer = lightmapTag("bitmaps").GetValue(lightMap, 2)
        '    Dim bFormat As Bitmap.bitmFormat = lightmapTag("bitmaps").GetValue(lightMap, 5)

        '    Dim bFlags As Bitmap.bitmType = lightmapTag("bitmaps").GetValue(lightMap, 6)


        '    Dim DestIndex As Integer = ((rY * BitmapWidth + rX) * 2 - 2)
        '    Array.Copy(BitConverter.GetBytes(BitConverter.ToInt16(BitConverter.GetBytes(comInt), 0)), 0, Raw, DestIndex, 2)
        '    If (bFlags And &H8) > 0 Then
        '        Select Case bFormat
        '            Case Bitmap.bitmFormat.BITM_FORMAT_DXT1
        '                Raw = Raw
        '            Case Bitmap.bitmFormat.BITM_FORMAT_DXT2AND3
        '                Raw = Raw
        '            Case Bitmap.bitmFormat.BITM_FORMAT_DXT4AND5
        '                Raw = Raw
        '            Case Bitmap.bitmFormat.BITM_FORMAT_A8
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 8, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_Y8
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 8, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_AY8
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 8, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_A8Y8
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 16, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_R5G6B5
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 16, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_A1R5G5B5
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 16, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_A4R4G4B4
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 16, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_X8R8G8B8
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 32, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_A8R8G8B8
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 32, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_P8
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 8, SwizzleType.Swizzle)
        '            Case Bitmap.bitmFormat.BITM_FORMAT_A8_LIGHTMAP
        '                Raw = Swizzle.Swizzle(Raw, BitmapWidth, BitmapHeight, -1, 8, SwizzleType.Swizzle)
        '        End Select
        '    End If
        'End If
    End Sub

    Private Sub CloseScenarioMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseScenarioMenu.Click
        If Not SelectedScenario Is Nothing Then
            SelectedScenario = Nothing
            GC.Collect()
        End If
    End Sub

    Private Sub CustomBitmapMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CustomBitmapMenuItem.Click
        If File.Exists("tool.exe") Then
            Dim OFD As New OpenFileDialog()
            If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then
                Dim DataFolder As New DirectoryInfo("data\")
                Dim TagsFolder As New DirectoryInfo("tags\")
                Dim BitmapsFolder As DirectoryInfo = DataFolder.CreateSubdirectory("levels\test\custom\bitmaps")
                Dim BittagsFolder As DirectoryInfo = TagsFolder.CreateSubdirectory("levels\test\custom\bitmaps")

                CreateBitmap(OFD.FileName, BitmapsFolder.FullName)

                Dim ToolEXE As New System.Diagnostics.Process()
                ToolEXE.StartInfo.WorkingDirectory = Application.StartupPath
                ToolEXE.StartInfo.RedirectStandardOutput = True
                ToolEXE.StartInfo.RedirectStandardError = True
                ToolEXE.StartInfo.UseShellExecute = False
                ToolEXE.StartInfo.CreateNoWindow = True
                ToolEXE.StartInfo.FileName = "tool.exe"
                ToolEXE.StartInfo.Arguments = "bitmaps " & BitmapsFolder.FullName.Replace(DataFolder.FullName, "")
                ToolEXE.Start()
                ToolEXE.WaitForExit()
                Console.WriteLine()
                Dim OutPut() As String = Split(ToolEXE.StandardOutput.ReadToEnd(), vbCrLf)
                For x As Integer = 0 To OutPut.Length - 1
                    ConsoleMessage(OutPut(x))
                Next
                ToolEXE.Dispose()
                ToolEXE = Nothing
                GC.Collect()

                If appSettings.XboxTagFolder <> TagsFolder.FullName Then
                    If Not Directory.Exists(appSettings.XboxTagFolder & "\levels\test\custom\bitmaps\") Then
                        Directory.CreateDirectory(appSettings.XboxTagFolder & "\levels\test\custom\bitmaps\")
                    End If
                    For Each dInfo As FileInfo In BittagsFolder.GetFiles()
                        If File.Exists((appSettings.XboxTagFolder & "\" & dInfo.FullName.Replace(TagsFolder.FullName, ""))) Then
                            File.Delete((appSettings.XboxTagFolder & "\" & dInfo.FullName.Replace(TagsFolder.FullName, "")))
                        End If
                        File.Move(dInfo.FullName, (appSettings.XboxTagFolder & "\" & dInfo.FullName.Replace(TagsFolder.FullName, "")))
                    Next
                End If
            End If
        Else
            MessageBox.Show("This feature requires tool.exe to reside in the working directory.", "Tool not found", MessageBoxButtons.OK, MessageBoxIcon.Stop)
        End If
    End Sub
    Sub CreateBitmap(ByVal Filename As String, ByVal DataDir As String)
        Dim OriginalMap As System.Drawing.Bitmap = New System.Drawing.Bitmap(Filename)

        Dim NewMap As System.Drawing.Bitmap = Nothing

        NewMap = ResizeMap(OriginalMap)
        NewMap.Save(DataDir & "\" & Path.GetFileNameWithoutExtension(Filename).Replace(" ", "_") & ".tiff", Imaging.ImageFormat.Tiff)
    End Sub
    Public Shared Function ResizeMap(ByVal oMap As System.Drawing.Bitmap) As System.Drawing.Bitmap
        Dim hSize As Integer = oMap.Height
        Dim wSize As Integer = oMap.Width

        Dim Po2 As Integer = 2
        Do Until Po2 >= hSize
            Po2 *= 2
        Loop
        hSize = Po2

        Po2 = 2
        Do Until Po2 >= wSize
            Po2 *= 2
        Loop
        wSize = Po2

        Return New System.Drawing.Bitmap(oMap, wSize, hSize)
    End Function

    Private Sub CacheToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CacheToolStripMenuItem.Click
        Dim nInternal As New frmInternal
        If nInternal.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            Dim OFD As New SaveFileDialog
            OFD.AddExtension = True
            OFD.DefaultExt = "map"
            OFD.Filter = "Halo Map (*.map)|*.map"

            If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then
                magicMap.SaveAsXbox(OFD.FileName, appSettings.PAL_Version, nInternal.Internal.Text, False)
            End If
        End If
    End Sub

    Private Sub CompressedToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompressedToolStripMenuItem.Click
        Dim nInternal As New frmInternal
        If nInternal.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            Dim OFD As New SaveFileDialog
            OFD.AddExtension = True
            OFD.DefaultExt = "map"
            OFD.Filter = "Halo Map (*.map)|*.map"

            If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then
                magicMap.SaveAsXbox(OFD.FileName, appSettings.PAL_Version, nInternal.Internal.Text, True)
            End If
        End If
    End Sub

    Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click
        If Not SelectedScenario Is Nothing Then
            SelectedScenario.SelectedBSPIndex = ToolStripComboBox1.SelectedIndex
        End If
    End Sub

    Private Sub ForceUpdateMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ForceUpdateMenuItem.Click
        If Directory.Exists(My.Application.Info.DirectoryPath & "\old\") Then
            Directory.Delete(My.Application.Info.DirectoryPath & "\old\", True)
        End If

        If Not My.Computer.Network.IsAvailable Then Exit Sub

        Try
            If Not My.Computer.Network.Ping("www.halomaps.com") Then Exit Sub
        Catch ex As System.Net.NetworkInformation.PingException
            Exit Sub
        End Try


        Dim BaseURL As String = "http://www.halomaps.com/downloads/halo/arsenic/updates/" '"http://www.cluis.net/programs/dsm/"
        Dim currentVersion As New Version(Application.ProductVersion)

        Dim wClient As New WebClient
        Dim sReader As StreamReader
        Try
            sReader = New StreamReader(wClient.OpenRead(BaseURL & "update.txt"))
        Catch ex As WebException
            Exit Sub
        End Try
        Dim versionString As String = sReader.ReadLine
        Dim remoteVersion As New Version(versionString)

        Dim numFiles As Integer = Convert.ToInt32(sReader.ReadLine())
        Dim tempFiles(numFiles - 1) As String
        For x As Integer = 0 To numFiles - 1
            tempFiles(x) = sReader.ReadLine
        Next
        Dim fUpdate As New frmUpdate()
        fUpdate.Label2.Text = "Version: " & versionString
        fUpdate.TextBox1.Text = sReader.ReadToEnd
        fUpdate.Button1.Focus()
        If fUpdate.ShowDialog = DialogResult.OK Then
            If Not Directory.Exists(Application.StartupPath & "\old\") Then
                Directory.CreateDirectory(Application.StartupPath & "\old\")
            End If
            Dim ProgressForm As New frmProgress
            ProgressForm.Text = "Updating..."
            ProgressForm.ProgressIcon = My.Resources.Arsenic48
            ProgressForm.Maximum = numFiles
            ProgressForm.Show()
            For x As Integer = 0 To numFiles - 1
                ProgressForm.Status = "Updating " & tempFiles(x)
                Application.DoEvents()
                ProgressForm.Progress += 1
                If File.Exists(Application.StartupPath & "\" & tempFiles(x)) Then
                    File.Move(Application.StartupPath & "\" & tempFiles(x), Application.StartupPath & "\old\" & tempFiles(x))
                End If
                wClient.DownloadFile(BaseURL & tempFiles(x), Application.StartupPath & "\" & tempFiles(x))
            Next
            ProgressForm.Close()
            ProgressForm.Dispose()
            'Me.Close()
            Application.Restart()
            'Process.Start(My.Application.Info.AssemblyName & ".exe", "updated")
        End If
    End Sub

    Private Sub frmMain_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove

    End Sub

    Private Sub RefreshButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshButton.Click
        RefreshFiles()
    End Sub

    Private Sub cmbScript_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbScript.SelectedIndexChanged
        If Not SelectedScenario Is Nothing Then
            ScriptBox.Text = ParseScript(Scripts.Scripts(cmbScript.SelectedIndex), SelectedScenario.scnrTag)
        End If
    End Sub

    Private Sub NoToolToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NoToolToolStripMenuItem.Click
        Dim OFD As New OpenFileDialog()
        If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then

            Dim image As System.Drawing.Bitmap = ResizeMap(New System.Drawing.Bitmap(OFD.FileName))
            Dim pFormat As Bitmap.bitmFormat = Bitmap.bitmFormat.BITM_FORMAT_A8R8G8B8
            Dim iFormat As Imaging.PixelFormat = image.PixelFormat
            Dim eitherOr As Short = 4
            Select Case image.PixelFormat
                Case Imaging.PixelFormat.Format16bppArgb1555
                    pFormat = Bitmap.bitmFormat.BITM_FORMAT_A1R5G5B5
                    eitherOr = 3
                Case Imaging.PixelFormat.Format16bppRgb565
                    pFormat = Bitmap.bitmFormat.BITM_FORMAT_R5G6B5
                    eitherOr = 3
                Case Imaging.PixelFormat.Format32bppArgb
                    pFormat = Bitmap.bitmFormat.BITM_FORMAT_A8R8G8B8
                    eitherOr = 4
                Case Imaging.PixelFormat.Format32bppRgb
                    pFormat = Bitmap.bitmFormat.BITM_FORMAT_X8R8G8B8
                    eitherOr = 4
                Case Else
                    pFormat = Bitmap.bitmFormat.BITM_FORMAT_A8R8G8B8
                    iFormat = Imaging.PixelFormat.Format32bppArgb
                    eitherOr = 4
            End Select

            Dim filename As String = appSettings.XboxTagFolder & "\levels\test\custom\bitmaps\" & Path.GetFileNameWithoutExtension(OFD.FileName) & ".bitmap"
            Dim bData As Imaging.BitmapData = image.LockBits(New Rectangle(0, 0, image.Width, image.Height), Imaging.ImageLockMode.ReadOnly, iFormat)
            'Get the address of the first line of the bitmap.
            Dim ptr As IntPtr = bData.Scan0

            ' Declare an array to hold the bytes of the bitmap.
            Dim numBytes As Integer = bData.Stride * image.Height
            Dim rgbValues(numBytes) As Byte

            ' Copy the RGB values into the array.
            Marshal.Copy(ptr, rgbValues, 0, numBytes)

            image.UnlockBits(bData)

            Dim b As New Magic.Core.Tag(Path.GetFileNameWithoutExtension(OFD.FileName), MagicInterface.cxpe.Item("bitm"))
            'b(1) = 0S
            b(3) = eitherOr
            b(5) = 1S
            'b(6) = 0S
            'b(12) = 0S
            b(19) = rgbValues ' Swizzle.Swizzle(rgbValues, image.Width, image.Height, 1, 32, SwizzleType.Swizzle)
            b(28) = b.Xpe.Children(28).AddBlock(b(28), -1)
            b(29) = b.Xpe.Children(29).AddBlock(b(29), -1)

            CType(b(28), Array).SetValue(1, 0, 2)


            CType(b(29), Array).SetValue(&H6269746DI, 0, 0)
            CType(b(29), Array).SetValue(CShort(image.Width), 0, 1)
            CType(b(29), Array).SetValue(CShort(image.Height), 0, 2)
            CType(b(29), Array).SetValue(1S, 0, 3)
            CType(b(29), Array).SetValue(pFormat, 0, 5)
            'CType(b(29), Array).SetValue(9S, 0, 6) 'swizzled
            CType(b(29), Array).SetValue(1S, 0, 6)
            CType(b(29), Array).SetValue(New Short() {image.Width / 2, image.Height / 2}, 0, 7)

            b.Write(filename, Nothing)
            RefreshFiles()
        End If
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        If Not SelectedScenario Is Nothing Then
            Dim OFD As New SaveFileDialog
            If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then
                Dim sW As New StreamWriter(OFD.FileName, False)
                Dim SBSP As Arsenic.BSP = SelectedScenario.BSPS(SelectedScenario.SelectedBSPIndex)
                For l As Integer = 0 To SBSP.Lightmaps.Count - 1
                    For m As Integer = 0 To SBSP.Lightmaps(l).Materials.Count - 1
                        sW.WriteLine("g " & l.ToString & "_" & m.ToString)
                        sW.WriteLine()
                        For v As Integer = 0 To SBSP.Lightmaps(l).Materials(m).Verts.Count - 1
                            sW.WriteLine("v " & SBSP.Lightmaps(l).Materials(m).Verts(v).X & " " & SBSP.Lightmaps(l).Materials(m).Verts(v).Y & " " & SBSP.Lightmaps(l).Materials(m).Verts(v).Z)
                        Next
                        sW.WriteLine()
                        For v As Integer = 0 To SBSP.Lightmaps(l).Materials(m).Verts.Count - 1
                            sW.WriteLine("vn " & SBSP.Lightmaps(l).Materials(m).Verts(v).nX & " " & SBSP.Lightmaps(l).Materials(m).Verts(v).nY & " " & SBSP.Lightmaps(l).Materials(m).Verts(v).nZ)
                        Next
                        sW.WriteLine()
                        For v As Integer = 0 To SBSP.Lightmaps(l).Materials(m).Verts.Count - 1
                            sW.WriteLine("vt " & SBSP.Lightmaps(l).Materials(m).Verts(v).u1 & " " & SBSP.Lightmaps(l).Materials(m).Verts(v).v1)
                        Next
                        sW.WriteLine()
                    Next
                Next
                Dim vertCount As Integer = 1
                For l As Integer = 0 To SBSP.Lightmaps.Count - 1
                    For m As Integer = 0 To SBSP.Lightmaps(l).Materials.Count - 1
                        sW.WriteLine("g " & l.ToString & "_" & m.ToString)

                        For f As Integer = 0 To SBSP.Lightmaps(l).Materials(m).Faces.Count / 3 - 1
                            Dim f1 As Short = SBSP.Lightmaps(l).Materials(m).Faces(f * 3) + vertCount
                            Dim f2 As Short = SBSP.Lightmaps(l).Materials(m).Faces(f * 3 + 1) + vertCount
                            Dim f3 As Short = SBSP.Lightmaps(l).Materials(m).Faces(f * 3 + 2) + vertCount

                            sW.WriteLine("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}", f1, f2, f3)
                        Next
                        sW.WriteLine()
                        vertCount += SBSP.Lightmaps(l).Materials(m).Verts.Count
                    Next
                Next
                sW.Close()
            End If

        End If
    End Sub

    Private Sub renderPanel_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles renderPanel.Paint

    End Sub
    Private Sub WriteJMS()
        If Not SelectedScenario Is Nothing Then
            Dim OFD As New SaveFileDialog
            If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then
                Dim sW As New StreamWriter(OFD.FileName, False)
                Dim SBSP As Arsenic.BSP = SelectedScenario.BSPS(SelectedScenario.SelectedBSPIndex)
                For l As Integer = 0 To SBSP.Lightmaps.Count - 1
                    For m As Integer = 0 To SBSP.Lightmaps(l).Materials.Count - 1
                        sW.WriteLine(SBSP.Lightmaps(l).Materials(m).Verts.Count)
                        For v As Integer = 0 To SBSP.Lightmaps(l).Materials(m).Verts.Count - 1
                            sW.WriteLine("0")
                            sW.WriteLine("{1}{0}{2}{0}{3}", vbTab, SBSP.Lightmaps(l).Materials(m).Verts(v).X * 100.0F, SBSP.Lightmaps(l).Materials(m).Verts(v).Y * 100.0F, SBSP.Lightmaps(l).Materials(m).Verts(v).Z * 100.0F)
                            sW.WriteLine("{1}{0}{2}{0}{3}", vbTab, SBSP.Lightmaps(l).Materials(m).Verts(v).nX, SBSP.Lightmaps(l).Materials(m).Verts(v).nY, SBSP.Lightmaps(l).Materials(m).Verts(v).nZ)
                            sW.WriteLine("-1")
                            sW.WriteLine("0")
                            sW.WriteLine(SBSP.Lightmaps(l).Materials(m).Verts(v).u1)
                            sW.WriteLine(SBSP.Lightmaps(l).Materials(m).Verts(v).v1)
                            sW.WriteLine("0")
                        Next
                    Next
                Next
                Dim vertCount As Integer = 0
                For l As Integer = 0 To SBSP.Lightmaps.Count - 1
                    For m As Integer = 0 To SBSP.Lightmaps(l).Materials.Count - 1
                        sW.WriteLine(SBSP.Lightmaps(l).Materials(m).Faces.Count / 3)

                        For f As Integer = 0 To SBSP.Lightmaps(l).Materials(m).Faces.Count / 3 - 1
                            Dim f1 As Short = SBSP.Lightmaps(l).Materials(m).Faces(f * 3) + vertCount
                            Dim f2 As Short = SBSP.Lightmaps(l).Materials(m).Faces(f * 3 + 1) + vertCount
                            Dim f3 As Short = SBSP.Lightmaps(l).Materials(m).Faces(f * 3 + 2) + vertCount
                            sW.WriteLine("0")
                            sW.WriteLine("0")
                            sW.WriteLine("{1}{0}{2}{0}{3}", vbTab, f1, f2, f3)
                        Next
                        vertCount += SBSP.Lightmaps(l).Materials(m).Verts.Count
                    Next
                Next
                sW.Close()
            End If

        End If
    End Sub
    Private Sub AddCubeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddCubeToolStripMenuItem.Click
        'WriteJMS()
        AddCubeBSP()
        Exit Sub
        Dim OFD As New OpenFileDialog
        OFD.AddExtension = True
        OFD.DefaultExt = "jms"
        OFD.Filter = "Fuck your cube (*.jms)|*.jms"

        If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            For x As Integer = 0 To magicMap.Library.Count - 1
                If magicMap.Library(x).Xpe.Extension = "scenario_structure_bsp" Then
                    Dim jmsReader As New StreamReader(OFD.FileName)
                    jmsReader.ReadLine() '8200
                    jmsReader.ReadLine() '3251
                    Dim nCount As Integer = jmsReader.ReadLine ' Node Count
                    For node As Integer = 0 To nCount - 1
                        jmsReader.ReadLine() 'name
                        jmsReader.ReadLine() 'index
                        jmsReader.ReadLine() 'index
                        jmsReader.ReadLine() 'rotation
                        jmsReader.ReadLine() 'translation
                    Next
                    nCount = jmsReader.ReadLine ' Materials Count
                    For node As Integer = 0 To nCount - 1
                        jmsReader.ReadLine() 'name
                        jmsReader.ReadLine() '<none>
                    Next
                    nCount = jmsReader.ReadLine ' Markers Count
                    For node As Integer = 0 To nCount - 1
                        jmsReader.ReadLine() 'name
                        jmsReader.ReadLine() '-1
                        jmsReader.ReadLine() 'index
                        jmsReader.ReadLine() 'rotation
                        jmsReader.ReadLine() 'translation
                        jmsReader.ReadLine() '2.0
                    Next
                    jmsReader.ReadLine() '1
                    jmsReader.ReadLine() 'unnamed

                    Dim numVerts As Integer = jmsReader.ReadLine

                    Dim dStream As New BinaryWriter(New MemoryStream)

                    For node As Integer = 0 To numVerts - 1
                        jmsReader.ReadLine() 'node0 index
                        Dim positionStr As String() = jmsReader.ReadLine().Split(vbTab) 'position
                        Dim normalStr As String() = jmsReader.ReadLine().Split(vbTab) 'normal
                        jmsReader.ReadLine() 'node1 index
                        jmsReader.ReadLine() 'node1 weight
                        Dim txcoordx As Single = jmsReader.ReadLine() 'txcoordx
                        Dim txcoordy As Single = jmsReader.ReadLine() 'txcoordy
                        jmsReader.ReadLine() '0
                        dStream.Write(CSng(positionStr(0)) * 0.01F)
                        dStream.Write(CSng(positionStr(1)) * 0.01F)
                        dStream.Write(CSng(positionStr(2)) * 0.01F)
                        dStream.Write(CSng(normalStr(0)))
                        dStream.Write(CSng(normalStr(1)))
                        dStream.Write(CSng(normalStr(2)))
                        dStream.Write(CSng(0))
                        dStream.Write(CSng(0))
                        dStream.Write(CSng(0))
                        dStream.Write(CSng(0))
                        dStream.Write(CSng(0))
                        dStream.Write(CSng(0))
                        dStream.Write(CSng(txcoordx))
                        dStream.Write(CSng(txcoordy))
                    Next
                    dStream.Seek(0, SeekOrigin.Begin)
                    Dim dBytes As Byte() = CType(dStream.BaseStream, MemoryStream).ToArray
                    Dim cBytes As Byte() = Magic.Core.HaloMap.CompressBspVertices(dBytes, False)

                    Dim bspSurfaces As Array = magicMap.Library(x).Item("surfaces")
                    Dim startingFaces As Integer = bspSurfaces.GetLength(0)
                    Dim numFaces As Integer = jmsReader.ReadLine
                    For node As Integer = 0 To numFaces - 1
                        jmsReader.ReadLine() '0
                        jmsReader.ReadLine() 'shader index
                        Dim vertStr As String() = jmsReader.ReadLine().Split(vbTab) 'verts

                        bspSurfaces = magicMap.Library(x).Xpe.FieldByName("surfaces").AddBlock(bspSurfaces, -1)
                        bspSurfaces.SetValue(CShort(vertStr(0)), bspSurfaces.GetLength(0) - 1, 0)
                        bspSurfaces.SetValue(CShort(vertStr(1)), bspSurfaces.GetLength(0) - 1, 1)
                        bspSurfaces.SetValue(CShort(vertStr(2)), bspSurfaces.GetLength(0) - 1, 2)
                    Next
                    magicMap.Library(x).Item("surfaces") = bspSurfaces

                    Dim bspLightmaps As Array = magicMap.Library(x).Item("structure lightmaps")
                    For b As Integer = 0 To bspLightmaps.GetLength(0) - 1
                        If bspLightmaps.GetValue(b, 0) = -1 Then
                            Dim bspMaterials As Array = bspLightmaps.GetValue(b, 3)
                            bspMaterials = magicMap.Library(x).Xpe.FieldByName("structure lightmaps").FieldByName("structure materials").AddBlock(bspMaterials, -1)
                            bspMaterials.SetValue(startingFaces, bspMaterials.GetLength(0) - 1, 3)
                            bspMaterials.SetValue(numFaces, bspMaterials.GetLength(0) - 1, 4)
                            bspMaterials.SetValue(New Integer() {1, numVerts, 0, 0}, bspMaterials.GetLength(0) - 1, 20)
                            bspMaterials.SetValue(New Integer() {3, 0, 0, 0}, bspMaterials.GetLength(0) - 1, 21)
                            bspMaterials.SetValue(New Magic.Core.Tag.DataContainer(0, dBytes), bspMaterials.GetLength(0) - 1, 22)
                            bspMaterials.SetValue(New Magic.Core.Tag.DataContainer(0, cBytes), bspMaterials.GetLength(0) - 1, 23)
                            bspLightmaps.SetValue(bspMaterials, b, 3)
                        End If
                    Next
                    magicMap.Library(x).Item("structure lightmaps") = bspLightmaps
                    Exit For
                End If
            Next
        End If
    End Sub
    Private Sub AddCubeBSP()
        'WriteJMS()

        Dim OFD As New OpenFileDialog
        OFD.AddExtension = True
        OFD.DefaultExt = "scenario_structure_bsp"
        OFD.Filter = "Fuck your cube (*.scenario_structure_bsp)|*.scenario_structure_bsp"

        If OFD.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            Dim ntag As New Magic.Core.Tag(OFD.FileName, Globals.appSettings.XboxTagFolder, magicMap.Library, appSettings.CETagFolder, False)
            For x As Integer = 0 To magicMap.Library.Count - 1
                If magicMap.Library(x).Xpe.Extension = "scenario_structure_bsp" Then

                    Dim newMatSurfaces As Array = ntag("surfaces")
                    Dim bspSurfaces As Array = magicMap.Library(x).Item("surfaces")
                    Dim startingFaces As Integer = bspSurfaces.GetLength(0)

                    For node As Integer = 0 To newMatSurfaces.GetLength(0) - 1
                        bspSurfaces = magicMap.Library(x).Xpe.FieldByName("surfaces").AddBlock(bspSurfaces, -1)
                        bspSurfaces.SetValue(newMatSurfaces.GetValue(node, 0), bspSurfaces.GetLength(0) - 1, 0)
                        bspSurfaces.SetValue(newMatSurfaces.GetValue(node, 1), bspSurfaces.GetLength(0) - 1, 1)
                        bspSurfaces.SetValue(newMatSurfaces.GetValue(node, 2), bspSurfaces.GetLength(0) - 1, 2)
                    Next
                    magicMap.Library(x).Item("surfaces") = bspSurfaces

                    Dim bspLightmaps As Array = magicMap.Library(x).Item("structure lightmaps")
                    Dim newMaterials As Array = ntag("structure lightmaps").GetValue(0, 3)
                    For b As Integer = 0 To bspLightmaps.GetLength(0) - 1
                        If bspLightmaps.GetValue(b, 0) = -1 Then
                            Dim bspMaterials As Array = bspLightmaps.GetValue(b, 3)
                            bspMaterials = magicMap.Library(x).Xpe.FieldByName("structure lightmaps").FieldByName("structure materials").AddBlock(bspMaterials, -1)
                            bspMaterials.SetValue(startingFaces, bspMaterials.GetLength(0) - 1, 3)
                            bspMaterials.SetValue(newMatSurfaces.GetLength(0), bspMaterials.GetLength(0) - 1, 4)
                            bspMaterials.SetValue(newMaterials.GetValue(0, 20), bspMaterials.GetLength(0) - 1, 20)
                            bspMaterials.SetValue(newMaterials.GetValue(0, 21), bspMaterials.GetLength(0) - 1, 21)
                            bspMaterials.SetValue(newMaterials.GetValue(0, 22), bspMaterials.GetLength(0) - 1, 22)
                            bspMaterials.SetValue(newMaterials.GetValue(0, 23), bspMaterials.GetLength(0) - 1, 23)
                            bspLightmaps.SetValue(bspMaterials, b, 3)
                            Exit For
                        End If
                    Next
                    magicMap.Library(x).Item("structure lightmaps") = bspLightmaps

                    Dim newCollision As Array = ntag("collision bsp")
                    Dim bspCollision As Array = magicMap.Library(x).Item("collision bsp")

                    Dim origBSP3D As Array = bspCollision.GetValue(0, 0)
                    Dim origPlanes As Array = bspCollision.GetValue(0, 1)
                    Dim origLeaves As Array = bspCollision.GetValue(0, 2)
                    Dim origBSP2DRef As Array = bspCollision.GetValue(0, 3)
                    Dim origBSP2DNode As Array = bspCollision.GetValue(0, 4)
                    Dim origSurfaces As Array = bspCollision.GetValue(0, 5)
                    Dim origEdges As Array = bspCollision.GetValue(0, 6)
                    Dim origVertices As Array = bspCollision.GetValue(0, 7)

                    Dim newBSP3D As Array = newCollision.GetValue(0, 0)
                    Dim newPlanes As Array = newCollision.GetValue(0, 1)
                    Dim newLeaves As Array = newCollision.GetValue(0, 2)
                    Dim newBSP2DRef As Array = newCollision.GetValue(0, 3)
                    Dim newBSP2DNode As Array = newCollision.GetValue(0, 4)
                    Dim newSurfaces As Array = newCollision.GetValue(0, 5)
                    Dim newEdges As Array = newCollision.GetValue(0, 6)
                    Dim newVertices As Array = newCollision.GetValue(0, 7)

                    Dim origBSP3DCount As Integer = origBSP3D.GetLength(0)
                    Dim origPlanesCount As Integer = origPlanes.GetLength(0)
                    Dim origLeavesCount As Integer = origLeaves.GetLength(0)
                    Dim origBSP2DRefCount As Integer = origBSP2DRef.GetLength(0)
                    Dim origBSP2DNodeCount As Integer = origBSP2DNode.GetLength(0)
                    Dim origSurfacesCount As Integer = origSurfaces.GetLength(0)
                    Dim origEdgesCount As Integer = origEdges.GetLength(0)
                    Dim origVerticesCount As Integer = origVertices.GetLength(0)


                    For node As Integer = 0 To newBSP3D.GetLength(0) - 1
                        origBSP3D = magicMap.Library(x).Xpe.FieldByName("collision bsp").FieldByName("bsp3d nodes").AddBlock(origBSP3D, -1)
                        origBSP3D.SetValue(newBSP3D.GetValue(node, 0) + origPlanesCount, origBSP3D.GetLength(0) - 1, 0)

                        If newBSP3D.GetValue(node, 1) > -1 Then
                            origBSP3D.SetValue(newBSP3D.GetValue(node, 1) + origBSP3DCount, origBSP3D.GetLength(0) - 1, 1)
                        ElseIf newBSP3D.GetValue(node, 1) = -1 Then
                            origBSP3D.SetValue(newBSP3D.GetValue(node, 1), origBSP3D.GetLength(0) - 1, 1)
                        Else
                            origBSP3D.SetValue(CInt(newBSP3D.GetValue(node, 1) + origLeavesCount), origBSP3D.GetLength(0) - 1, 1)
                        End If

                        If newBSP3D.GetValue(node, 2) > -1 Then
                            origBSP3D.SetValue(newBSP3D.GetValue(node, 2) + origBSP3DCount, origBSP3D.GetLength(0) - 1, 2)
                        ElseIf newBSP3D.GetValue(node, 2) = -1 Then
                            origBSP3D.SetValue(newBSP3D.GetValue(node, 2), origBSP3D.GetLength(0) - 1, 2)
                        Else
                            origBSP3D.SetValue(CInt(newBSP3D.GetValue(node, 2) + origLeavesCount), origBSP3D.GetLength(0) - 1, 2)
                        End If
                    Next
                    bspCollision.SetValue(origBSP3D, 0, 0)

                    For node As Integer = 0 To newPlanes.GetLength(0) - 1
                        origPlanes = magicMap.Library(x).Xpe.FieldByName("collision bsp").FieldByName("planes").AddBlock(origPlanes, -1)
                        origPlanes.SetValue(newPlanes.GetValue(node, 0), origPlanes.GetLength(0) - 1, 0)
                    Next
                    bspCollision.SetValue(origPlanes, 0, 1)

                    For node As Integer = 0 To newLeaves.GetLength(0) - 1
                        origLeaves = magicMap.Library(x).Xpe.FieldByName("collision bsp").FieldByName("leaves").AddBlock(origLeaves, -1)
                        origLeaves.SetValue(newLeaves.GetValue(node, 0), origLeaves.GetLength(0) - 1, 0)
                        origLeaves.SetValue(newLeaves.GetValue(node, 1), origLeaves.GetLength(0) - 1, 1)
                        origLeaves.SetValue(newLeaves.GetValue(node, 2) + origBSP2DRefCount, origLeaves.GetLength(0) - 1, 2)
                    Next
                    bspCollision.SetValue(origLeaves, 0, 2)

                    For node As Integer = 0 To newBSP2DRef.GetLength(0) - 1
                        origBSP2DRef = magicMap.Library(x).Xpe.FieldByName("collision bsp").FieldByName("bsp2d references").AddBlock(origBSP2DRef, -1)
                        origBSP2DRef.SetValue(newBSP2DRef.GetValue(node, 0) + origPlanesCount, origBSP2DRef.GetLength(0) - 1, 0)

                        If newBSP2DRef.GetValue(node, 1) > -1 Then
                            origBSP2DRef.SetValue(newBSP2DRef.GetValue(node, 1) + origBSP2DNodeCount, origBSP2DRef.GetLength(0) - 1, 1)
                        ElseIf newBSP2DRef.GetValue(node, 1) = -1 Then
                            origBSP2DRef.SetValue(newBSP2DRef.GetValue(node, 1), origBSP2DRef.GetLength(0) - 1, 1)
                        Else
                            origBSP2DRef.SetValue(CInt(newBSP2DRef.GetValue(node, 1) + origSurfacesCount), origBSP2DRef.GetLength(0) - 1, 1)
                        End If
                    Next
                    bspCollision.SetValue(origBSP2DRef, 0, 3)

                    For node As Integer = 0 To newSurfaces.GetLength(0) - 1
                        origSurfaces = magicMap.Library(x).Xpe.FieldByName("collision bsp").FieldByName("surfaces").AddBlock(origSurfaces, -1)
                        origSurfaces.SetValue(newSurfaces.GetValue(node, 0) + origPlanesCount, origSurfaces.GetLength(0) - 1, 0)
                        origSurfaces.SetValue(newSurfaces.GetValue(node, 1) + origEdgesCount, origSurfaces.GetLength(0) - 1, 1)
                        origSurfaces.SetValue(newSurfaces.GetValue(node, 2), origSurfaces.GetLength(0) - 1, 2)
                        origSurfaces.SetValue(newSurfaces.GetValue(node, 3), origSurfaces.GetLength(0) - 1, 3)
                        origSurfaces.SetValue(newSurfaces.GetValue(node, 4), origSurfaces.GetLength(0) - 1, 4)
                    Next
                    bspCollision.SetValue(origSurfaces, 0, 5)


                    For node As Integer = 0 To newEdges.GetLength(0) - 1
                        origEdges = magicMap.Library(x).Xpe.FieldByName("collision bsp").FieldByName("edges").AddBlock(origEdges, -1)
                        origEdges.SetValue(newEdges.GetValue(node, 0) + origVerticesCount, origEdges.GetLength(0) - 1, 0)
                        origEdges.SetValue(newEdges.GetValue(node, 1) + origVerticesCount, origEdges.GetLength(0) - 1, 1)
                        origEdges.SetValue(newEdges.GetValue(node, 2) + origEdgesCount, origEdges.GetLength(0) - 1, 2)
                        origEdges.SetValue(newEdges.GetValue(node, 3) + origEdgesCount, origEdges.GetLength(0) - 1, 3)
                        origEdges.SetValue(newEdges.GetValue(node, 4) + origSurfacesCount, origEdges.GetLength(0) - 1, 4)
                        origEdges.SetValue(newEdges.GetValue(node, 5) + origSurfacesCount, origEdges.GetLength(0) - 1, 5)
                    Next
                    bspCollision.SetValue(origEdges, 0, 6)

                    For node As Integer = 0 To newVertices.GetLength(0) - 1
                        origVertices = magicMap.Library(x).Xpe.FieldByName("collision bsp").FieldByName("vertices").AddBlock(origVertices, -1)
                        origVertices.SetValue(newVertices.GetValue(node, 0), origVertices.GetLength(0) - 1, 0)
                        origVertices.SetValue(newVertices.GetValue(node, 1) + origEdgesCount, origVertices.GetLength(0) - 1, 1)
                    Next
                    bspCollision.SetValue(origVertices, 0, 7)

                    magicMap.Library(x).Item("collision bsp") = bspCollision

                    Dim newNodes As Array = ntag("nodes")
                    Dim bspNodes As Array = magicMap.Library(x).Item("nodes")
                    Dim origNodeCount As Integer = bspNodes.GetLength(0)
                    For node As Integer = 0 To newNodes.GetLength(0) - 1
                        bspNodes = magicMap.Library(x).Xpe.FieldByName("nodes").AddBlock(bspNodes, -1)
                        bspNodes.SetValue(newNodes.GetValue(node, 0), bspNodes.GetLength(0) - 1, 0)
                    Next
                    magicMap.Library(x).Item("nodes") = bspNodes


                    Dim newLeafSurfaaces As Array = ntag("leaf surfaces")
                    Dim bspLeafSurfaces As Array = magicMap.Library(x).Item("leaf surfaces")
                    Dim origLeafSurfaceCount As Integer = bspLeafSurfaces.GetLength(0)
                    For node As Integer = 0 To newLeafSurfaaces.GetLength(0) - 1
                        bspLeafSurfaces = magicMap.Library(x).Xpe.FieldByName("leaf surfaces").AddBlock(bspLeafSurfaces, -1)
                        bspLeafSurfaces.SetValue(newLeafSurfaaces.GetValue(node, 0) + startingFaces, bspLeafSurfaces.GetLength(0) - 1, 0)
                        bspLeafSurfaces.SetValue(newLeafSurfaaces.GetValue(node, 1) + origNodeCount, bspLeafSurfaces.GetLength(0) - 1, 1)
                    Next
                    magicMap.Library(x).Item("leaf surfaces") = bspLeafSurfaces


                    Dim newCluster As Array = ntag("clusters")
                    Dim bspCluster As Array = magicMap.Library(x).Item("clusters")
                    Dim origClusterCount As Integer = bspCluster.GetLength(0)
                    For node As Integer = 0 To newCluster.GetLength(0) - 1
                        bspCluster = magicMap.Library(x).Xpe.FieldByName("clusters").AddBlock(bspCluster, -1)

                        bspCluster.SetValue(newCluster.GetValue(node, 0), bspCluster.GetLength(0) - 1, 0)
                        bspCluster.SetValue(newCluster.GetValue(node, 1), bspCluster.GetLength(0) - 1, 1)
                        bspCluster.SetValue(newCluster.GetValue(node, 2), bspCluster.GetLength(0) - 1, 2)
                        bspCluster.SetValue(newCluster.GetValue(node, 3), bspCluster.GetLength(0) - 1, 3)
                        bspCluster.SetValue(newCluster.GetValue(node, 4), bspCluster.GetLength(0) - 1, 4)
                        bspCluster.SetValue(newCluster.GetValue(node, 5), bspCluster.GetLength(0) - 1, 5)
                        Dim newSubClusters As Array = newCluster.GetValue(node, 9)

                        For subCluster As Integer = 0 To newSubClusters.GetLength(0) - 1
                            Dim subClusterSurfaces As Array = newSubClusters.GetValue(subCluster, 3)
                            For subClusterIndice As Integer = 0 To subClusterSurfaces.GetLength(0) - 1
                                Dim indice As Integer = subClusterSurfaces.GetValue(subClusterIndice, 0) + startingFaces
                                subClusterSurfaces.SetValue(indice, subClusterIndice, 0)
                            Next
                            newSubClusters.SetValue(subClusterSurfaces, subCluster, 3)
                        Next
                        bspCluster.SetValue(newSubClusters, bspCluster.GetLength(0) - 1, 9)
                        bspCluster.SetValue(newCluster.GetValue(node, 10), bspCluster.GetLength(0) - 1, 10)
                        bspCluster.SetValue(newCluster.GetValue(node, 11), bspCluster.GetLength(0) - 1, 11)

                    Next
                    magicMap.Library(x).Item("clusters") = bspCluster


                    Dim newBSPLeaves As Array = ntag("leaves")
                    Dim bspLeaves As Array = magicMap.Library(x).Item("leaves")
                    For node As Integer = 0 To newBSPLeaves.GetLength(0) - 1
                        bspLeaves = magicMap.Library(x).Xpe.FieldByName("leaves").AddBlock(bspLeaves, -1)
                        bspLeaves.SetValue(newBSPLeaves.GetValue(node, 0), bspLeaves.GetLength(0) - 1, 0)
                        bspLeaves.SetValue(newBSPLeaves.GetValue(node, 1), bspLeaves.GetLength(0) - 1, 1)
                        bspLeaves.SetValue(newBSPLeaves.GetValue(node, 2) + origClusterCount, bspLeaves.GetLength(0) - 1, 2)
                        bspLeaves.SetValue(newBSPLeaves.GetValue(node, 3), bspLeaves.GetLength(0) - 1, 3)
                        bspLeaves.SetValue(newBSPLeaves.GetValue(node, 4) + origLeafSurfaceCount, bspLeaves.GetLength(0) - 1, 4)
                    Next
                    magicMap.Library(x).Item("leaves") = bspLeaves

                    '-<Block index="0" maxelements="131072" size="12" offset="0" description="bsp3d node" name="bsp3d nodes">
                    '-<Block index="1" maxelements="65536" size="16" offset="12" description="plane" name="planes">
                    '-<Block index="2" maxelements="65536" size="8" offset="24" description="leaf" name="leaves">
                    '-<Block index="3" maxelements="131072" size="8" offset="36" description="bsp2d reference" name="bsp2d references">
                    '-<Block index="4" maxelements="65535" size="20" offset="48" description="bsp2d node" name="bsp2d nodes">
                    '-<Block index="5" maxelements="131072" size="12" offset="60" description="surface" name="surfaces">
                    '-<Block index="6" maxelements="262144" size="24" offset="72" description="edge" name="edges">
                    '-<Block index="7" maxelements="131072" size="16" offset="84" description="vertex" name="vertices">



                    magicMap.Library(x).Dirty()
                    magicMap.SaveAsTagCollection(appSettings.XboxTagFolder, True)
                    Exit For
                End If
            Next
        End If
    End Sub
End Class
